package com.cj.mobile.iabp.mvp.ui.activity;

import static com.jess.arms.utils.Preconditions.checkNotNull;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.KeyboardUtils;
import com.cj.mobile.iabp.R;
import com.cj.mobile.iabp.app.dialog.PopupSelectFinancial;
import com.cj.mobile.iabp.app.utils.CommonUtils;
import com.cj.mobile.iabp.app.utils.DecimalInputUtils;
import com.cj.mobile.iabp.app.utils.EventBusTags;
import com.cj.mobile.iabp.di.component.DaggerAddPatientComponent;
import com.cj.mobile.iabp.mvp.contract.AddPatientContract;
import com.cj.mobile.iabp.mvp.model.entity.DeptInfo;
import com.cj.mobile.iabp.mvp.model.entity.DictInfo;
import com.cj.mobile.iabp.mvp.model.entity.MainEvent;
import com.cj.mobile.iabp.mvp.model.entity.PatientInfo;
import com.cj.mobile.iabp.mvp.presenter.AddPatientPresenter;
import com.cj.mobile.iabp.mvp.ui.adapter.PrimaryDiagnosisAdapter;
import com.cj.mobile.iabp.mvp.ui.adapter.SecondaryDiagnosisAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created on 2025/09/24 15:36
 * 添加患者 或 修改患者
 *
 * @author Love_xie
 * module name is AddPatientActivity
 */
public class AddPatientActivity extends BaseActivity<AddPatientPresenter> implements AddPatientContract.View {
    /*----------------------------------------------------------------控件信息----------------------------------------------------------------*/

    @BindView(R.id.tab_addpatient_group)
    RadioGroup radioGroup;                                                                          // 院区
    @BindView(R.id.radio_addpatient_chaoyang)
    RadioButton radioCY;
    @BindView(R.id.radio_addpatient_tongzhou)
    RadioButton radioTZ;


    @BindView(R.id.edit_addpatient_install)
    EditText editInstall;                                                                           // 安装次数

    @BindView(R.id.edit_addpatient_register)
    EditText editRegister;                                                                          // 登记号

    @BindView(R.id.edit_addpatient_name)
    EditText editName;                                                                              // 患者姓名

    @BindView(R.id.edit_addpatient_height)
    EditText editHeight;                                                                            // 身高

    @BindView(R.id.edit_addpatient_weight)
    EditText editWeight;                                                                            // 体重

    @BindView(R.id.txvi_addpatient_sex)
    TextView txviSex;                                                                               // 性别

    @BindView(R.id.edit_addpatient_age)
    EditText editAge;                                                                               // 年龄

    @BindView(R.id.edti_addpatient_otherdiagnosis)
    EditText editOtherDiagnosis;                                                                    // 其它诊断

    @BindView(R.id.txvi_addpatient_department)
    TextView txviDepartment;                                                                        // 科室

    @BindView(R.id.edti_addpatient_ward)
    EditText editWard;                                                                              // 所在病房

    @BindView(R.id.edti_addpatient_bunk)
    EditText editBunk;                                                                              // 所在床位

    @BindView(R.id.edti_addpatient_contact)
    EditText editContact;                                                                           // 患者联系人

    @BindView(R.id.edti_addpatient_phone)
    EditText editPhone;                                                                             // 联系人电话

    @BindView(R.id.revi_addpatient_primarydiagnosis)
    RecyclerView reviPrimaryDiagnosis;

    @BindView(R.id.txvi_addpatient_primarydiagnosis)
    TextView txviPrimaryDiagnosis;

    @BindView(R.id.revi_addpatient_secondarydiagnosis)
    RecyclerView reviSecondaryDiagnosis;

    @BindView(R.id.txvi_addpatient_secondarydiagnosis)
    TextView txviSecondaryDiagnosis;

    /*----------------------------------------------------------------业务信息----------------------------------------------------------------*/
    // 对话框
    private MaterialDialog mDialog;
    // 性别 弹框
    private PopupSelectFinancial mPopupSex;
    // 科室 弹框
    private PopupSelectFinancial mPopupDepartment;

    @Named("PrimaryLayout")
    @Inject
    RecyclerView.LayoutManager mPrimaryLayoutManager;
    @Named("PrimaryAdapter")
    @Inject
    PrimaryDiagnosisAdapter mPrimaryAdapter;

    @Named("SecondaryLayout")
    @Inject
    RecyclerView.LayoutManager mSecondaryLayoutManager;
    @Named("SecondaryAdapter")
    @Inject
    SecondaryDiagnosisAdapter mSecondaryAdapter;

    // 院区id
    private String mCampusId;
    // 科室id
    private String mDepartmentId;
    // 性别：1男  2女  9其它
    private String mSexId;

    @Override
    protected void onDestroy() {
        KeyboardUtils.unregisterSoftInputChangedListener(getWindow());
        if (mDialog != null) {
            this.mDialog.dismiss();
        }
        super.onDestroy();

        this.mDialog = null;
        this.mPopupSex = null;
        this.mPopupDepartment = null;
    }

    /**
     * 根据主题使用不同的颜色。
     * 如果想要纯透明，则需要重写此方法，返回值为 -1 即可。
     */
    public int useStatusBarColor() {
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(android.R.color.white, typedValue, true);
        return typedValue.data;
    }

    /**
     * 将状态栏改为浅色模式(状态栏 icon 和字体会变成深色)
     */
    public boolean useLightStatusBar() {
        return true;
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerAddPatientComponent
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_add_patient;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        // 初始化Loading对话框
        mDialog = new MaterialDialog.Builder(this).content(R.string.common_execute).progress(true, 0).build();

        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.radio_addpatient_chaoyang:
                    mCampusId = "2";
                    break;
                case R.id.radio_addpatient_tongzhou:
                    mCampusId = "3";
                    break;
            }

            if (mPresenter != null) {
                mPresenter.getDepartmentList(mCampusId);
            }
        });
        initRecyclerView();
        loadSex();

        // 创建输入框数组
        EditText[] decimalInputs = {editHeight, editWeight};
        // 批量设置，限制小数点后2位
        DecimalInputUtils.setupDecimalInputs(decimalInputs, 2);


        if (mPresenter != null) {
            mPresenter.initData(getIntent().getExtras());
        }
    }

    private void initRecyclerView() {
        ArmsUtils.configRecyclerView(reviPrimaryDiagnosis, mPrimaryLayoutManager);
        reviPrimaryDiagnosis.setAdapter(mPrimaryAdapter);
        mPrimaryAdapter.setOnItemClickListener((view, viewType, data, position) -> {
            DictInfo info = (DictInfo) data;
            primaryData(info);
        });


        ArmsUtils.configRecyclerView(reviSecondaryDiagnosis, mSecondaryLayoutManager);
        reviSecondaryDiagnosis.setAdapter(mSecondaryAdapter);
        mSecondaryAdapter.setOnItemClickListener((view, viewType, data, position) -> {
            DictInfo info = (DictInfo) data;
            info.setCheckBox(!info.isCheckBox());
        });
    }

    @Subscriber(tag = EventBusTags.HOME_TAG, mode = ThreadMode.POST)
    private void eventBusEvent(MainEvent mainEvent) {
        if (mainEvent.getCode() == EventBusTags.REFRESH_HOME_INFO_TAG) {
            // 主要诊断
            primaryData(mainEvent.getInfo());
        }
    }

    /**
     * 处理主要诊断数据，只能选一项
     */
    private void primaryData(DictInfo info) {
        for (DictInfo item : mPrimaryAdapter.getInfos()) {
            item.setCheckBox(false);
        }

        info.setCheckBox(true);

        mPrimaryAdapter.notifyDataSetChanged();
    }

    @OnClick({
            R.id.txvi_addpatient_sex,                                                               // 性别
            R.id.txvi_addpatient_department,                                                        // 科室
            R.id.btn_addpatient_save,                                                               // 暂存
            R.id.btn_addpatient_submit,                                                             // 提交
    })
    @Override
    public void onClick(View v) {
        super.onClick(v);
        hideInput();
        switch (v.getId()) {
            case R.id.txvi_addpatient_sex:                                                          // 性别
                if (mPopupSex != null) {
                    mPopupSex.showAtLocation(v, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
                }
                break;
            case R.id.txvi_addpatient_department:                                                   // 科室
                if (mCampusId == null || mCampusId.equals("")) {
                    showMessage("请先选择院区！");
                } else {
                    if (mPopupDepartment != null) {
                        mPopupDepartment.showAtLocation(v, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
                    } else {
                        showMessage("暂无所属科室数据，请联系管理员！");
                    }
                }
                break;
            case R.id.btn_addpatient_save:                                                          // 暂存
                if (!CommonUtils.isDoubleClick()) {
                    onSubmit("0");
                }
                break;
            case R.id.btn_addpatient_submit:                                                        // 提交
                if (!CommonUtils.isDoubleClick()) {
                    onSubmit("1");
                }
                break;
        }
    }

    private void onSubmit(String pre) {
        if (mPresenter != null) {
            mPresenter.btnSubmit(pre, mCampusId,
                    editInstall.getText().toString(),
                    editRegister.getText().toString(),
                    editName.getText().toString(),
                    editHeight.getText().toString(),
                    editWeight.getText().toString(),
                    mSexId,
                    editAge.getText().toString(),
                    mPresenter.getPrimaryDiagnosis(),
                    editOtherDiagnosis.getText().toString(),
                    mPresenter.getSecondaryDiagnosis(),
                    mDepartmentId,
                    editWard.getText().toString(),
                    editBunk.getText().toString(),
                    editContact.getText().toString(),
                    editPhone.getText().toString()
            );
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        hideInput();
        return super.onTouchEvent(event);
    }

    /**
     * 隐藏软键盘
     */
    private void hideInput() {
        KeyboardUtils.hideSoftInput(this);
    }

    /**
     * 性别
     */
    public void loadSex() {
        List<String> mShow = new ArrayList<>();
        mShow.add("男");
        mShow.add("女");

        PopupSelectFinancial.ItemClick itemClick = (position, name) -> {
            this.mSexId = name.equals("男") ? "1" : "2";
            txviSex.setText(name);
        };
        mPopupSex = new PopupSelectFinancial(this, "性别", mShow, itemClick);
    }

    @Override
    public void showLoadingSubmit() {
        if (mDialog != null)
            mDialog.show();
    }

    @Override
    public void hideLoadingSubmit() {
        if (mDialog != null)
            mDialog.hide();
    }

    /**
     * 加载科室
     */
    @Override
    public void loadDepartment(List<DeptInfo> mList) {
        if (CommonUtils.isNotEmpty(mList)) {
            List<String> mShow = new ArrayList<>();

            for (DeptInfo info : mList) {
                mShow.add(info.getName());
            }

            PopupSelectFinancial.ItemClick itemClick = (position, name) -> {
                DeptInfo info = mList.get(position);
                this.txviDepartment.setText(CommonUtils.isEmptyReturnStr(info.getName()));
                this.mDepartmentId = String.valueOf(info.getId());
            };
            mPopupDepartment = new PopupSelectFinancial(this, "所属科室", mShow, itemClick);
        }
    }

    /**
     * 诊断没有数据
     */
    @Override
    public void notDiagnosis() {
        txviPrimaryDiagnosis.setVisibility(View.VISIBLE);
        txviSecondaryDiagnosis.setVisibility(View.VISIBLE);
    }

    @Override
    public void loadDefaultData(PatientInfo info) {
        if (info != null) {

            this.mCampusId = info.getDeptSec();
            if (!TextUtils.isEmpty(info.getDeptSec())) {
                if (info.getDeptSec().equals("2")) {
                    radioCY.setChecked(true);
                } else {
                    radioTZ.setChecked(true);
                }
            }

            editInstall.setText(CommonUtils.isEmptyReturnStr(info.getCnt()));
            editRegister.setText(CommonUtils.isEmptyReturnStr(info.getCode()));
            editName.setText(CommonUtils.isEmptyReturnStr(info.getName()));
            editHeight.setText(CommonUtils.isEmptyReturnStr(info.getHeight()));
            editWeight.setText(CommonUtils.isEmptyReturnStr(info.getWeight()));

            this.mSexId = info.getSex();
            if (TextUtils.isEmpty(info.getSex())) {
                txviSex.setText("");
            } else {
                if (info.getSex().equals("1")) {
                    txviSex.setText("男");
                } else if (info.getSex().equals("2")) {
                    txviSex.setText("女");
                } else {
                    txviSex.setText("其它");
                }
            }
            editAge.setText(CommonUtils.isEmptyReturnStr(info.getAge()));
            editOtherDiagnosis.setText(CommonUtils.isEmptyReturnStr(info.getDiagnose()));
            this.mDepartmentId = CommonUtils.isEmptyReturnStr(info.getDeptId());
            txviDepartment.setText(CommonUtils.isEmptyReturnStr(info.getDeptName()));
            editWard.setText(CommonUtils.isEmptyReturnStr(info.getArea()));
            editBunk.setText(CommonUtils.isEmptyReturnStr(info.getBedNo()));
            editContact.setText(CommonUtils.isEmptyReturnStr(info.getFriends()));
            editPhone.setText(CommonUtils.isEmptyReturnStr(info.getPhone()));
        }
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void showLoading() {
        txviPrimaryDiagnosis.setVisibility(View.GONE);
        txviSecondaryDiagnosis.setVisibility(View.GONE);
    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }
}